package com.ruoyi.web.controller.order;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.order.domain.OrderInfo;
import com.ruoyi.order.service.IOrderService;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.io.FileUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController extends BaseController {

    @Autowired
    private IOrderService orderService;

    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult fileUpload(@RequestParam("file") MultipartFile file) throws Exception {

        List<OrderInfo> list = orderService.upload(file);

        return success(list);
    }

    /**
     * 根据条件分页查询订单数据
     *
     * @param orderinfo 查询条件
     * @return 订单数据集合信息
     */
    @PreAuthorize("@ss.hasPermi('order:search:list')")
    @GetMapping("/list")
    public TableDataInfo searchOrderList(OrderInfo orderinfo) {
        startPage();
        List<Map<String, Object>> List = orderService.searchOrderList(orderinfo);
        return getDataTable(List);
    }

    /**
     * 通过订单ID查询订单详细
     *
     * @param orderId 订单ID
     * @return 订单详细
     */
    @PreAuthorize("@ss.hasPermi('order:search:query')")
    @GetMapping(value = "/{orderId}")
    public AjaxResult getInfo(@PathVariable Long orderId) {
        return success(orderService.selectOrderById(orderId));
    }

    /**
     * 修改订单状态
     *
     * @param orderIds 订单ID数组
     * @param model    更新区分（2：接单 3：投产 4：完成 5：发货）
     * @return 更新结果
     */
    @Log(title = "订单台账", businessType = BusinessType.UPDATE)
    @PutMapping("updateOrderState/{orderIds}")
    public AjaxResult updateOrderState(@PathVariable Long[] orderIds, @RequestParam String model) {
        int updateCnt = orderService.updateOrderStateByIds(orderIds, model);
        return updateCnt == orderIds.length ? AjaxResult.success("下单成功") : AjaxResult.error("下单失败");
    }

    /**
     * 删除订单
     *
     * @param orderIds 订单ID数组
     * @return 删除结果
     */
    @PreAuthorize("@ss.hasPermi('order:search:remove')")
    @Log(title = "订单台账", businessType = BusinessType.DELETE)
    @DeleteMapping("/{orderIds}")
    public AjaxResult delete(@PathVariable Long[] orderIds) {
        return toAjax(orderService.deleteOrderByIds(orderIds));
    }

    /**
     * 订单文件下载
     *
     * @param fileId   文件ID
     * @param response
     * @throws Exception 异常
     */
    @RequestMapping(value = "/download/{fileId}", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public void downloadFile(@PathVariable String fileId, HttpServletResponse response) throws Exception {
        // 查询文件详细
        Map<String, Object> file = orderService.selectFileById(fileId);
        String filePath = "";
        if (file != null) {
            filePath = file.get("filePath") + "//" + file.get("fileName");
        }
        File file1 = new File(filePath);

        // 文件路径不存在
        if (!file1.getParentFile().exists()) {
            // 创建路径
            file1.getParentFile().mkdirs();
        }

        // 文件不存在
        if (!file1.exists()) {
            //创建excel工作蒲
            XSSFWorkbook workbook = new XSSFWorkbook();

            //创建一个工作表sheet
            XSSFSheet sheet = workbook.createSheet();
            //创建第一行
            XSSFRow row = sheet.createRow(0);
            //定义cell
            XSSFCell cell = null;
            cell = row.createCell(0);
            cell.setCellValue(file.get("fileName").toString());

            //创建一个文件
            file1.createNewFile();
            //将excel内容存盘
            FileOutputStream stream = FileUtils.openOutputStream(file1);
            workbook.write(stream);
            stream.close();
        }

        FileInputStream in = null;
        ServletOutputStream out = null;
        in = new FileInputStream(filePath);
        response.setCharacterEncoding("UTF-8");
        // 设置强制下载不打开
        response.setContentType("application/force-download");
        out = response.getOutputStream();
        IOUtils.copy(in, out);
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }

}
